<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit"/>
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <title>你画我猜</title>
    <link rel="stylesheet" href="./css/main.css">
    <link rel="stylesheet" href="./css/home.css">
    <link rel="stylesheet" href="./css/game.css">
    <script src="./js/jquery-3.7.1.min.js"></script>
</head>

<body>
<div id="page-box">
    <!-- 主页 -->
    <div id="page-home">
        <div id="home-title">
            <h1>你画我猜</h1>
            <label for="player-id">昵称</label><input type="text" id="player-id" class="input"
                                                      placeholder="请输入玩家昵称"/>
            <button class="button" onclick="createPlayer()">创建</button>
        </div>

        <div id="room-list-box">
            <span id="room-item-title">房间列表</span>
            <div id="room-list">
            </div>
        </div>
        <div style="width: 100%;display: flex;justify-content: center;">
            <button class="button" onclick="getRooms()">刷新列表</button>
            <button class="button" onclick="createRoom()">创建房间</button>
        </div>
        <button class="button" onclick="goGame()">切换到游戏页面</button>
    </div>

    <!-- 游戏页面 -->
    <div id="page-game">
        <div id="game-top-box">
            <button id="back-btn" class="button"><span class="iconfont">&#xe65d;</span></button>
            <button id="userIcon" class="button">玩家：admin</button>
        </div>
        <div id="draw-box">
            <div id="topic-bar">
                <div>题目：<span id="topic-name">坐井观天</span></div>
                <div>提示：<span id="topic-tip">成语，四个字</span></div>
            </div>
            <canvas id="board" width="600" height="600"></canvas>
            <div style="display: flex;width: 100%;justify-content: space-between;padding: 0 15px 10px 15px;box-sizing: border-box;">
                <div>
                    <!--颜色-->
                    <button id="color-select-btn" class="control-btn" onclick="toggleColorBox()"><span class="iconfont">&#xe6da;</span></button>
                    <!--粗细-->
                    <button id="width-select-btn" class="control-btn" onclick="toggleWidthBox()"><span class="iconfont">&#xe641;</span></button>
                    <!--橡皮-->
                    <button id="eraser-select-btn" class="control-btn" onclick="toggleEraserBox()"><span class="iconfont">&#xe61b;</span></button>
                </div>
                <div>
                    <!--清空-->
                    <button class="control-btn" onclick="sendClearDraw()"><span class="iconfont">&#xe60b;</span>
                    </button>
                </div>
            </div>
            <!--颜色选择框-->
            <div id="color-select-box" class="select-box">
                <span style="font-size: 1.5em;" class="iconfont">&#xe6da;</span>
                <button class="color-btn" data-color="#000000"
                        style="background-color: #000000;border-color: #ffffff;"></button>
                <button class="color-btn" data-color="#ff1744"
                        style="background-color: #ff1744;"></button>
                <button class="color-btn" data-color="#00c853"
                        style="background-color: #00c853;"></button>
                <button class="color-btn" data-color="#2962ff"
                        style="background-color: #2962ff;"></button>
                <button class="color-btn" data-color="#ffd600"
                        style="background-color: #ffd600;"></button>
            </div>
            <!--画笔粗细选择框-->
            <div id="width-select-box" class="select-box">
                <span style="font-size: 1.5em;" class="iconfont">&#xe641;</span>
                <button class="width-btn" data-width="8"
                        style="border-color: #ffffff;width: 8px;height: 8px;"></button>
                <button class="width-btn" data-width="12"
                        style="width: 12px;height: 12px;"></button>
                <button class="width-btn" data-width="16"
                        style="width: 16px;height: 16px;"></button>
                <button class="width-btn" data-width="20"
                        style="width: 20px;height: 20px;"></button>
                <button class="width-btn" data-width="24"
                        style="width: 24px;height: 24px;"></button>
            </div>
            <!--橡皮粗细选择框-->
            <div id="eraser-select-box" class="select-box">
                <span style="font-size: 1.5em;" class="iconfont">&#xe61b;</span>
                <button class="eraser-btn" data-width="8"
                        style="border-color: #ffffff;width: 8px;height: 8px;"></button>
                <button class="eraser-btn" data-width="12"
                        style="width: 12px;height: 12px;"></button>
                <button class="eraser-btn" data-width="16"
                        style="width: 16px;height: 16px;"></button>
                <button class="eraser-btn" data-width="20"
                        style="width: 20px;height: 20px;"></button>
                <button class="eraser-btn" data-width="24"
                        style="width: 24px;height: 24px;"></button>
            </div>
        </div>

        <div id="player-box">
            <div class="player-item">张</div>
            <div class="player-item">王</div>
            <div class="player-item"></div>
            <div class="player-item"></div>
            <div class="player-item"></div>
        </div>
        <div id="chat-box">

        </div>
        <div id="chat-input-box">
            <input id="chat-input" type="text" autocomplete="off" placeholder="输入文字以发送" class="input"/>
            <button class="button" onclick="sendInput()">发送</button>
        </div>

    </div>
</div>

</body>

</html>

<script>
    // WebSocket实例
    let ws = null;
    // 当前玩家id
    let playerId = "";
    // 当前房间id
    let roomId = "";
    const backendAddr = "192.168.31.222:8080"
    // const backendAddr = "draw.airnan.cn"
    const api = "http://" + backendAddr + "/api"
    // const api = "https://" + backendAddr + "/api"


    init();

    function init() {
        window.addEventListener("beforeunload", (event) => {
            // Cancel the event as stated by the standard.
            event.preventDefault();
            // Chrome requires returnValue to be set.
            event.returnValue = "";
        });
        isHasWS();
        getLocalPlayer();
        getRooms();
    }

    /**
     * 判断WebSocket是否可用
     */
    function isHasWS() {
        if ("WebSocket" in window) {
            console.log("WebSocket可用");
        } else {
            alert("浏览器不支持WebSocket，无法进行游戏，请尝试其他浏览器");
            $("body").hide();
        }
    }

    /**
     * 获取本地玩家信息
     */
    function getLocalPlayer() {
        playerId = window.localStorage.getItem("playerId");
        if (playerId === undefined || playerId === null || playerId === "") {
            playerId = "";
        } else {
            // 本地存在时判断服务端是否还在
            $.ajax({
                url: api + "/player/isExist",
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({id: playerId}),
                success: function (data) {
                    if (data.code === 0) {
                        if (data.data === true) {
                            $("#player-id").val(playerId);
                        } else {
                            window.localStorage.removeItem("playerId");
                            showMsg("服务端玩家已注销，请重新创建！");
                        }
                    } else {
                        showMsg(data.msg)
                    }
                },
                error: function (xhr, status, error) {
                    // 请求失败时的处理逻辑
                    console.error('请求失败：', status, error);
                }
            });
        }

    }

    /**
     * 创建玩家
     */
    function createPlayer() {
        let postData = {
            id: $("#player-id").val().trim()
        }
        if (postData.id == null || postData.id == undefined || postData.id == "") {
            return showMsg("玩家昵称不能为空！")
        }
        $.ajax({
            url: api + "/player/create",
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(postData),
            success: function (data) {
                if (data.code === 0) {
                    showMsg("创建成功！");
                    window.localStorage.setItem("playerId", postData.id);
                    playerId = postData.id;
                } else {
                    showMsg(data.msg)
                }
            },
            error: function (xhr, status, error) {
                // 请求失败时的处理逻辑
                console.error('请求失败：', status, error);
            }
        });
    }

    /**
     * 获取房间列表
     */
    function getRooms() {
        $("#room-list").html("");
        $.ajax({
            url: api + "/room/list",
            type: 'GET',
            success: function (data) {
                // 成功接收到响应后的处理逻辑
                showMsg("房间列表已刷新");
                if (data.code === 0) {
                    let roomsData = data.data;
                    if (!Array.isArray(roomsData) || roomsData.length === 0) {
                        $("#room-list").html("—— 暂无房间 ——")
                    }
                    $.each(roomsData, function (index, room) {
                        // 创建房间元素
                        var $roomItem = $('<div class="room-item"></div>');
                        var $roomInfo = $('<div></div>');
                        var $roomName = $('<span class="room-item-room">' + room.id + '</span>');
                        var $playerInfo = $('<span class="room-item-player">@' + room.master + '</span>');
                        var $joinButton = $('<button class="button">加入房间</button>');

                        // 将房间名称和玩家信息添加到房间信息元素中
                        $roomInfo.append($roomName);
                        $roomInfo.append($playerInfo);

                        // 将房间信息和加入按钮添加到房间元素中
                        $roomItem.append($roomInfo);
                        $roomItem.append($joinButton);

                        // 将房间元素添加到页面中
                        $("#room-list").append($roomItem);

                        // 绑定按钮点击事件
                        $joinButton.on('click', function () {
                            if (playerId === "") {
                                return showMsg("请先创建玩家！");
                            }
                            var result = confirm("确定要加入房间【" + room.id + "】吗？");
                            if (result) {
                                joinRoom(room.id);
                            } else {
                                showMsg("取消操作")
                            }
                        });
                    });
                }
            },
            error: function (xhr, status, error) {
                // 请求失败时的处理逻辑
                console.error('请求失败：', status, error);
            }
        });
    }

    function createRoom() {
        if (playerId === "") {
            return showMsg("请先创建玩家！");
        }
        let createInput = window.prompt("请输入房间名称：", "");
        if (createInput !== null) {
            if (createInput.trim() === "") {
                return showMsg("房间名不能为空！")
            }
            $.ajax({
                url: api + "/room/create",
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({id: createInput, master: playerId}),
                success: function (data) {
                    if (data.code === 0) {
                        showMsg("创建成功！");
                        var result = confirm("创建成功,是否现在进入房间【" + createInput + "】？");
                        if (result) {
                            joinRoom(createInput)
                        }
                        getRooms();
                    } else {
                        showMsg(data.msg)
                    }
                },
                error: function (xhr, status, error) {
                    // 请求失败时的处理逻辑
                    console.error('请求失败：', status, error);
                }
            });
        }
    }

    function showMsg(message) {
        var $toast = $('<div class="toast"></div>').text(message).hide();
        $('body').append($toast);
        $toast.fadeIn(100);
        setTimeout(function () {
            $toast.fadeOut(100);
            setTimeout(function () {
                $toast.remove();
            }, 600);
        }, 2000);
    }

    function joinRoom(rid) {
        // 判断是否可以加入
        $.ajax({
            url: api + "/room/canJoin",
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({id: rid, players: [{id: playerId}]}),
            success: function (data) {
                if (data.code === 0) {
                    let url = "ws://" + backendAddr + "/websocket/" + playerId + "/" + rid;
                    // let url = "wss://" + backendAddr + "/websocket/" + playerId + "/" + rid;
                    // 打开一个 web socket
                    ws = new WebSocket(url);
                    ws.onopen = function () {
                        roomId = rid;
                        // 发送握手消息
                        sendMessage("room-chat", playerId + "：大家好，我是" + playerId);
                        goGame();
                    };
                    ws.onmessage = function (evt) {
                        let result = JSON.parse(evt.data);
                        // 接收到通知消息
                        if (result.type === "room-msg") {
                            showMsg(result.data);
                        }
                        // 接收聊天消息
                        if (result.type === "room-chat") {
                            $("#chat-box").append("<p>" + result.data + "</p>")
                        }
                        // 接收绘画消息
                        if (result.type === "room-draw") {
                            let brush = JSON.parse(result.data);
                            if (brush.isPoint) {
                                brushPoint = {x: brush.x, y: brush.y}
                                drawPoint(brush.x, brush.y, brush.width, brush.color);
                            } else {
                                // 移动端若按下事件坐标为空，则在划线事件中处理，将新的坐标作为点补充画点事件
                                if (brushPoint.x == null || brushPoint.y == null) {
                                    drawPoint(brush.x, brush.y, brush.width, brush.color);
                                    brushPoint = {x: brush.x, y: brush.y};
                                    return;
                                }
                                drawLine(brushPoint, {
                                    x: brush.x,
                                    y: brush.y
                                }, brush.width, brush.color);
                                brushPoint = {x: brush.x, y: brush.y};
                            }
                        }
                        // 接收清空画板消息
                        if (result.type === "room-draw-clear") {
                            clearDraw();
                        }

                    };
                    ws.onclose = function () {
                        // 关闭 websocket
                        ws = null;
                        roomId = "";
                    };
                    ws.onerror = function (err) {
                        showMsg("加入失败，请重试");
                        roomId = "";
                    }
                } else {
                    showMsg(data.msg)
                }
            },
            error: function (xhr, status, error) {
                // 请求失败时的处理逻辑
                console.error('请求失败：', status, error);
            }
        });

    }

    /**
     * 停止WebSocket
     */
    function StopWS() {
        if (ws !== null) {
            ws.close();
            ws = null;
            roomId = "";
        }
        document.getElementById("image").src = "";
    }

    /**
     * 向服务端发送消息
     */
    function sendMessage(type, data) {
        if (getWsState() !== 1) {
            return showMsg("WebSocket未连接，无法发送消息！");
        }
        let msg = {
            type,
            playerId,
            roomId,
            data,
        };
        ws.send(JSON.stringify(msg));
    }

    /**
     * 获取WebSocket状态
     * 0 (WebSocket.CONNECTING)正在链接中
     * 1 (WebSocket.OPEN)已经链接并且可以通讯
     * 2 (WebSocket.CLOSING)连接正在关闭
     * 3 (WebSocket.CLOSED)连接已关闭或者没有链接成功
     */
    function getWsState() {
        if (ws === null) {
            return 3;
        } else {
            return ws.readyState;
        }
    }

    function sendInput() {
        let txt = $("#chat-input").val().trim();
        if (txt !== "") {
            sendMessage("room-chat", playerId + "：" + txt);
            $("#chat-input").val("");
        }
    }

    // 监听键盘事件
    document.getElementById('chat-input').addEventListener('keydown', function (event) {
        // 判断是否按下回车键（键码为13）
        if (event.keyCode === 13) {
            // 处理回车键事件
            sendInput();
        }
    });
    // 监听输入框的键盘事件
    document.getElementById('chat-input').addEventListener('input', function (event) {
        // 判断是否按下回车键
        if (event.inputType === 'insertLineBreak') {
            // 处理回车键事件
            sendInput();
        }
    });

    function goGame() {
        $("#page-box").css("left", "-100vw");
        $("#userIcon").html("玩家：" + playerId);
    }

    function goHome() {
        $("#page-box").css("left", "0px");
    }


</script>

<script src="./js/draw.js"></script>